package com.btobtob.a.biz.user.controller;

import com.alibaba.cola.dto.SingleResponse;
import com.btobtob.a.biz.user.converter.Demo3Converter;
import com.btobtob.a.biz.user.dto.clientobject.Demo3CO;
import com.btobtob.a.biz.user.dto.clientobject.WeatherForecastCO;
import com.btobtob.a.biz.user.dto.command.Demo3Cmd;
import com.btobtob.a.biz.user.dto.command.WeatherForecastCmd;
import com.btobtob.a.biz.user.grpc.Demo3Impl;
import com.btobtob.a.biz.user.protocol.Demo3Grpc;
import com.btobtob.a.biz.user.protocol.Demo3Reply;
import com.btobtob.a.biz.user.protocol.Demo3Request;
import com.google.type.DateTime;
import io.dapr.client.domain.HttpExtension;
import io.grpc.*;
import io.grpc.stub.MetadataUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

@Slf4j
@RestController
@Tag(name = "/grpc/j", description = "/grpc/j")
@RequestMapping("/grpc/j")
@Validated
@ResponseBody
public class GrpcJController {

    private static final Logger logger = LoggerFactory.getLogger(GrpcJController.class);

    @Resource
    private Demo3Converter demo3Converter;

    @PostMapping(value = "/post3")
    public SingleResponse<Demo3CO> post3(@RequestBody Demo3Cmd cmd) throws Exception {

        String target = "localhost:" + System.getenv("DAPR_GRPC_PORT");

        ManagedChannel channel = Grpc.newChannelBuilder(target, InsecureChannelCredentials.create()).build();

        try {
            Demo3Grpc.Demo3BlockingStub blockingStub = Demo3Grpc.newBlockingStub(channel);

            Metadata headers = new Metadata();
            headers.put(Metadata.Key.of("dapr-app-id", Metadata.ASCII_STRING_MARSHALLER), "btobtob-a-j-user");
            blockingStub = blockingStub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(headers));

            Demo3Request request = demo3Converter.from(cmd);
            Demo3Reply reply = blockingStub.post3(request);
            Demo3CO co = demo3Converter.to(reply);
            return SingleResponse.of(co);
        } finally {
            // To prevent leaking resources like threads and TCP connections
            // the channel should be shut down when it will no longer be used.
            channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
        }
    }

}
